<template>
  <div class="main-con">
    <el-form :model="query" :inline="true" label-width="80px" class="search-con">
      <el-form-item label="动态ID">
        <el-input v-model="query.recommendId" placeholder="请输入动态ID" clearable />
      </el-form-item>
      <el-form-item label="状态" style="width: 200px">
        <el-select v-model="query.publishStatus" placeholder="请选择状态" clearable>
          <el-option label="待审核" :value="0" />
          <el-option label="审核通过" :value="1" />
          <el-option label="审核拒绝" :value="2" />
        </el-select>
      </el-form-item>
      <el-form-item label="发布时间">
        <el-date-picker
          v-model="date"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="YYYY-MM-DD"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="search">查询</el-button>
        <el-button @click="reset">重置</el-button>
      </el-form-item>
    </el-form>

    <div class="table-container">
      <el-table
        :data="tableData.list"
        v-loading="loading"
        element-loading-text="加载中"
        style="width: 100%"
        border
      >
        <el-table-column label="动态id" width="180">
          <template #default="scope">
            <div class="user-info">
              <span class="nickname">{{ scope.row.recommendId }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="buyerUserId" label="发布者id" width="180" align="center" />
        <el-table-column label="动态内容" min-width="300">
          <template #default="scope">
            <div class="content-preview">
              <div class="content-text">{{ scope.row.remark }}</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100" align="center">
          <template #default="scope">
            <el-tag v-if="scope.row.publishStatus === 0" type="warning">待审核</el-tag>
            <el-tag v-else-if="scope.row.publishStatus === 1" type="success">审核通过</el-tag>
            <el-tag v-else-if="scope.row.publishStatus === 2" type="danger">审核拒绝</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="browseCount" label="浏览数" width="80" align="center" />
        <el-table-column prop="likeCount" label="点赞数" width="80" align="center" />
        <el-table-column prop="commentCount" label="评论数" width="80" align="center" />
        <el-table-column prop="shareCount" label="分享" width="80" align="center" />
        <el-table-column prop="publishTime" label="发布时间" width="160" align="center" />
        <el-table-column label="操作" align="center" width="150" fixed="right">
          <template #default="scope">
            <el-button link type="primary" @click="details(scope.row)">详情</el-button>
            <el-button
              v-if="scope.row.publishStatus === 0"
              link
              type="success"
              @click="toAudit(scope.row)"
              >审核</el-button
            >

          </template>
        </el-table-column>
      </el-table>
    </div>

    <div class="pagination-wrapper">
      <el-pagination
        :current-page="query.page"
        :page-size="query.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="tableData.total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handlePageChange($event, 'pageSize')"
        @current-change="handlePageChange($event, 'page')"
        class="pagination"
      />
    </div>

    <el-dialog v-model="visible" title="内容审核" width="500px" class="audit-dialog">
      <el-form ref="formRef" :model="formData" :rules="rules" label-width="80px">
        <el-form-item label="审核结果" prop="reviewStatus">
          <el-radio-group v-model="formData.reviewStatus">
            <el-radio :label="1">通过</el-radio>
            <el-radio :label="2">拒绝</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="formData.reviewStatus === 2" label="拒绝原因" prop="reason">
          <el-input v-model="formData.reason" type="textarea" placeholder="请输入拒绝原因" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="close">取消</el-button>
          <el-button type="primary" @click="audit(formRef)">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <dynamic-info ref="infoRef" />
  </div>
</template>

<script setup lang="ts">
  import { ref, onBeforeMount } from 'vue'
  import { Search } from '@element-plus/icons-vue'
  import { ElMessage, FormInstance } from 'element-plus'
  import { ContentService, ContentItem } from '@/api/contentApi'
  import DynamicInfo from './dynamicInfo.vue'

  const loading = ref(false)
  const formRef = ref<FormInstance | null>(null)
  const infoRef = ref<InstanceType<typeof DynamicInfo> | null>(null)
  const date = ref<[string, string] | []>([])
  const visible = ref(false)

  const defaultQuery = {
    page: 1,
    pageSize: 10,
    recommendId: '',
    publishStatus: undefined as number | undefined,
    publishStartTime: undefined as string | undefined,
    publishEndTime: undefined as string | undefined
  }

  const query = ref({ ...defaultQuery })

  const tableData = ref({
    list: [] as ContentItem[],
    total: 0,
    page: 1,
    pageSize: 10
  })

  const defaultFormData = {
    recommendId: '',
    reviewStatus: 1,
    reason: ''
  }

  const formData = ref({ ...defaultFormData })

  const rules = ref({
    reviewStatus: [{ required: true, message: '请选择审核结果', trigger: 'change' }],
    reason: [{ required: true, message: '请输入拒绝原因', trigger: 'blur' }]
  })

  onBeforeMount(() => {
    search()
  })

  const search = async () => {
    loading.value = true
    console.log('search()被调用了')
    try {
      if (date.value && date.value.length === 2) {
        console.log('date')
        query.value.publishStartTime = date.value[0] + ' 00:00:00'
        query.value.publishEndTime = date.value[1] + ' 23:59:59'
      } else {
        console.log('date.value')
        query.value.publishStartTime = undefined
        query.value.publishEndTime = undefined
      }
      console.log('亲求开始发送了')

      const response = await ContentService.contentQuery(query.value)
      console.log('请求成功了')
      console.log('完整响应:', response)

      // 检查响应数据结构，根据code判断是否成功
      if (response && response.code === '200' && response.data) {
        console.log('data:', response.data)
        // 确保必要的属性存在，使用查询参数中的page和pageSize
        const dataWithDefaults = {
          list: response.data.list || [],
          total: response.data.total || 0,
          page: query.value.page || 1,
          pageSize: query.value.pageSize || 10
        }
        tableData.value = dataWithDefaults
      } else {
        console.warn('响应数据结构不正确:', response)
        // 设置默认值以避免错误
        tableData.value = {
          list: [],
          total: 0,
          page: query.value.page || 1,
          pageSize: query.value.pageSize || 10
        }
      }
    } catch (error) {
      console.error('获取内容列表失败:', error)
      // 发生错误时设置默认值
      tableData.value = {
        list: [],
        total: 0,
        page: query.value.page || 1,
        pageSize: query.value.pageSize || 10
      }
    } finally {
      loading.value = false
    }
  }

  const reset = () => {
    console.log('重置了')
    date.value = []
    query.value = { ...defaultQuery }
    console.log('开始执行search()')
    search()
    console.log('search()执行完成')
  }

  const handlePageChange = (val: number, type: 'page' | 'pageSize') => {
    query.value[type] = val
    search()
  }

  // 审核
  const toAudit = (row: ContentItem) => {
    visible.value = true
    formData.value.recommendId = row.recommendId || ''
  }

  const audit = (formEl: FormInstance | null) => {
    if (!formEl) return

    formEl.validate((valid) => {
      if (valid) {
        submitAudit()
      }
    })
  }

  const submitAudit = async () => {
    try {
      await ContentService.contentAudit(formData.value)
      close()
      search()
      ElMessage({
        message: '审核成功',
        type: 'success'
      })
    } catch (error) {
      console.error('审核失败:', error)
    }
  }

  const close = () => {
    visible.value = false
    formData.value = { ...defaultFormData }
  }



  const details = (row: ContentItem) => {
    infoRef.value?.getInfo(row)
  }
</script>

<style lang="scss" scoped>
  .main-con {
    padding: 20px;
    margin-top: 20px;
    background: var(--art-bg-color);

    .search-con {
      padding: 20px;
      background: var(--art-gray-100);
      border-radius: 4px;
    }

    .user-info {
      display: flex;
      gap: 10px;
      align-items: center;

      .nickname {
        font-size: 14px;
      }
    }

    .content-preview {
      .image-list {
        display: flex;
        gap: 10px;
        margin-bottom: 10px;
      }

      .content-image {
        width: 80px;
        height: 80px;
        border-radius: 4px;
      }

      .content-video {
        width: 100%;
        max-width: 300px;
        height: auto;
      }

      .content-text {
        margin-top: 10px;
        font-size: 14px;
        line-height: 1.5;
      }
    }

    .table-container {
      overflow-x: auto;
      overflow-y: auto;
      touch-action: pan-y;
    }

    .pagination-wrapper {
      overflow-x: auto;
      overflow-y: hidden;
      touch-action: pan-x;
      padding: 0 10px;
      margin-top: 20px;
    }

    .pagination {
      justify-content: flex-start !important;
      min-width: 0;
      margin: 0 !important;
      padding: 0 10px !important;
    }
  }

  :deep(.audit-dialog) {
    .t-center {
      padding-top: 10px;
      margin-bottom: 20px;
      text-align: center;
    }

    .el-dialog__header {
      padding: 0;
      background-color: var(--art-bg-color);

      .el-dialog__close {
        color: rgb(0 0 0 / 50%);
      }

      .el-dialog__headerbtn:focus,
      .el-dialog__headerbtn:hover {
        .el-dialog__close {
          color: var(--art-primary);
        }
      }
    }
  }
</style>
